﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERP.ERPSystem.HumanResources.Dto;
using ERP.Team.HumanResources;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Volo.Abp;
using Volo.Abp.Account;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.HumanResources
{
    public  class JobGradeManagementServices:ApplicationService,IJobGradeManagementServices
    {
        private readonly IRepository<JobGradeManagement, int> _jobServices;
        private readonly ILogger<JobGradeManagementServices> _logger;

        public JobGradeManagementServices(
            IRepository<JobGradeManagement, int> jobServices,
            ILogger<JobGradeManagementServices> logger)
        {
            _jobServices = jobServices;
            _logger = logger;
        }

        /// <summary>
        /// 添加职级管理
        /// </summary>
        /// <param name="jobGradeDto"></param>
        /// <returns></returns>
       public async Task<int> AddJobGrade(JobGradeDto jobGradeDto )
        {
            var job = ObjectMapper.Map<JobGradeDto, JobGradeManagement>(jobGradeDto);
            var i=await _jobServices.InsertAsync(job);
            return i == null ? 0 : 1;
        }

        /// <summary>
        /// 显示职级管理
        /// </summary>
        /// <returns></returns>
        public async Task<List<JobGradeManagement>> GetJobGrades()
        {
            var jobGradelist = await _jobServices.GetListAsync();
            return jobGradelist;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteJobGradee(int id)
        {
            await _jobServices.DeleteAsync(id);
        }

        public async Task<JobGradeDto> GetJobGradeByIdAsync(int id)
        {
            var jobGrade = await _jobServices.GetAsync(id);
            if (jobGrade == null)
            {
                throw new UserFriendlyException("未找到指定职级");
            }
            return ObjectMapper.Map<JobGradeManagement, JobGradeDto>(jobGrade);
        }

        public async Task UpdateJobGradeAsync(JobGradeDto input)
        {
            var jobGrade = await _jobServices.GetAsync(input.Id);
            if (jobGrade == null)
            {
                throw new UserFriendlyException("未找到指定职级");
            }

            // 验证薪资范围
            if (input.SalaryRangelower >= input.SalaryRangelimits)
            {
                throw new UserFriendlyException("薪资范围上限必须大于下限");
            }

            // 更新实体
            ObjectMapper.Map(input, jobGrade);
            await _jobServices.UpdateAsync(jobGrade);
        }

        public async Task<byte[]> ExportJobGrades(
            string jobGradeCoding = null,
            string jobGradeLevel = null,
            string jobGradeLevelName = null,
            int? salaryRangelower = null,
            int? salaryRangelimits = null)
        {
            try
            {
                // 构建查询条件
                var query = await _jobServices.GetQueryableAsync();
                var queryable = query.AsQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(jobGradeCoding))
                {
                    queryable = queryable.Where(x => x.JobGradeCoding.Contains(jobGradeCoding));
                }

                if (!string.IsNullOrWhiteSpace(jobGradeLevel))
                {
                    queryable = queryable.Where(x => x.JobGradeLevel.Contains(jobGradeLevel));
                }

                if (!string.IsNullOrWhiteSpace(jobGradeLevelName))
                {
                    queryable = queryable.Where(x => x.JobGradeLevelName.Contains(jobGradeLevelName));
                }

                if (salaryRangelower.HasValue)
                {
                    queryable = queryable.Where(x => x.SalaryRangelower >= salaryRangelower.Value);
                }

                if (salaryRangelimits.HasValue)
                {
                    queryable = queryable.Where(x => x.SalaryRangelimits <= salaryRangelimits.Value);
                }

                var data = queryable.ToList();

                // 创建Excel工作簿
                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("职级管理");

                // 创建表头
                var headerRow = sheet.CreateRow(0);
                var headers = new[] { "职级编码", "职级层次", "职级层次名称", "薪资范围下限", "薪资范围上限", "备注" };
                for (var i = 0; i < headers.Length; i++)
                {
                    var cell = headerRow.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                }

                // 填充数据
                for (var i = 0; i < data.Count; i++)
                {
                    var row = sheet.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(data[i].JobGradeCoding ?? "");
                    row.CreateCell(1).SetCellValue(data[i].JobGradeLevel ?? "");
                    row.CreateCell(2).SetCellValue(data[i].JobGradeLevelName ?? "");
                    row.CreateCell(3).SetCellValue(data[i].SalaryRangelower);
                    row.CreateCell(4).SetCellValue(data[i].SalaryRangelimits);
                    row.CreateCell(5).SetCellValue(data[i].ReferenceColumn ?? "");
                }

                // 自动调整列宽
                for (var i = 0; i < headers.Length; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                // 将工作簿转换为字节数组
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    return ms.ToArray();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出职级管理数据出错");
                throw new UserFriendlyException("导出数据失败，请稍后重试");
            }
        }
    }
}
